<template>
  <div class="content-box">
    <div class="container" style="width: 1000px; margin: 0 auto">
      <div>
        <button @click="printEditorHtml">获取编辑器html</button>
        <button @click="getEditorText">获取编辑器文本</button>
      </div>
      <div style="border: 1px solid #ccc; margin-top: 10px; text-align: left">
        <!-- 工具栏 -->
        <Toolbar
          style="border-bottom: 1px solid #ccc"
          :editor="editor"
          :defaultConfig="toolbarConfig"
        />
        <!-- 编辑器 -->
        <Editor
          style="height: 500px; overflow-y: hidden"
          :defaultConfig="editorConfig"
          v-model="html"
          @onChange="onChange"
          @onCreated="onCreated"
          @onFocus="handleFocus"
        />
      </div>
      <div style="margin-top: 10px">
        <textarea
          v-model="html"
          readonly
          style="width: 100%; height: 200px; outline: none"
        ></textarea>
      </div>
    </div>
  </div>
</template>

<script>
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import kityformula from "@/components/kityformula";
import myscriptMath from "@/components/myscriptMath";
import { Boot } from "@wangeditor/editor";
import formulaModule from "@wangeditor/plugin-formula";
export default {
  name: "MyEditor",
  components: { Editor, Toolbar },
  data() {
    return {
      editor: null,
      html: "<p>hello&nbsp;world</p>",
      toolbarConfig: {
        // 插入编辑公式菜单
        insertKeys: {
          index: 0,
          keys: [
            "insertFormula", // “插入公式”菜单
            "kityFormula", // “编辑公式”菜单
            "myscriptMath",
          ],
        },
        // excludeKeys: [ /* 隐藏哪些菜单 */ ],
      },
      editorConfig: {
        placeholder: "请输入内容...",
        // autoFocus: false,

        // 所有的菜单配置，都要在 MENU_CONF 属性下
        MENU_CONF: {},
      },
    };
  },
  methods: {
    onCreated(editor) {
      console.log("created", editor);
      this.editor = Object.seal(editor); // 【注意】一定要用 Object.seal() 否则会报错
    },
    onChange(editor) {
      console.log("onChange", editor.getHtml()); // onChange 时获取编辑器最新内容
    },
    handleFocus(editor) {
      console.log("focus", editor);
    },
    getEditorText() {
      const editor = this.editor;
      if (editor == null) return;

      console.log(editor.getText()); // 执行 editor API
    },
    printEditorHtml() {
      const editor = this.editor;
      if (editor == null) return;

      console.log(editor.getHtml()); // 执行 editor API
    },
  },
  created() {
    Boot.registerMenu(kityformula);
    Boot.registerMenu(myscriptMath);
    Boot.registerModule(formulaModule);
  },
  mounted() {
    // 模拟 ajax 请求，异步渲染编辑器
    setTimeout(() => {
      this.html = "<p>Ajax 异步设置内容 HTML</p>";
    }, 1500);
  },
  beforeDestroy() {
    const editor = this.editor;
    if (editor == null) return;
    editor.destroy(); // 组件销毁时，及时销毁 editor ，重要！！！
  },
};
</script>

<style src="@wangeditor/editor/dist/css/style.css"></style>
